package com.zslibrary.BusMaster;

import com.zslibrary.Enum.Protocol;
import com.zslibrary.Pipe.StreamPipe;
import com.zslibrary.Structure.GeneralRequestStruct;
import com.zslibrary.Structure.MessageStruct;
import com.zslibrary.Structure.SensorValueStruct;
import com.zslibrary.Tools.FrameBuilder;

public class BusGetSensorValue {
    private static SensorValueStruct sensorValue;
    public static int getSensorValue(StreamPipe pipe, int componentId, int sensor){
        GeneralRequestStruct gRequest=new GeneralRequestStruct();
        FrameBuilder builder=new FrameBuilder(4);

        gRequest.requstId= Protocol.MSG_REQUEST_SENSOR_VALUE;
        gRequest.dataLength=4;
        builder.append((short)componentId);
        builder.append((short)sensor);
        gRequest.data=builder.toBytes();

        if(!pipe.synchronousPipe(gRequest)){
            return -1;
        }

        StreamPipe.ValidReply onValid=new StreamPipe.ValidReply() {
            @Override
            public Boolean isValid(MessageStruct message) {
                switch(message.messageId){
                    case Protocol.MSG_GET_SENSOR_VALUE:{
                        FrameBuilder msgBuilder=new FrameBuilder(message.messageData);
                        SensorValueStruct value=new SensorValueStruct();
                        value.componentId=(short)msgBuilder.popData(2);
                        value.sensorIndex=(short)msgBuilder.popData(2);
                        value.value=msgBuilder.popData(4);
                        sensorValue=value;
                        return true;
                    }

                    default:
                        break;
                }
                return false;
            }
        };

        if(!pipe.asychronousPipe(1000,onValid))
            return -1;
        if(sensorValue!=null)
            return sensorValue.value;
        return -1;
    }
}
